<template>
    <el-form :inline="true" ref="ruleFormRef" :model="ruleForm" status-icon :rules="rules" label-width="120px"
        class="demo-ruleForm">
        <!-- 验证码输入框 -->
        <el-form-item label="验证码" prop="verifiCode">
            <el-input v-model="ruleForm.verifiCode" type="text" autocomplete="off" />
        </el-form-item>
        <!-- 验证码图片 -->
        <el-form-item>
            <el-image style="width: 130px; height: 33px" @click="getVerifiCode" :src="url" />
        </el-form-item>
        <!-- 按钮 -->
        <el-form-item>
            <el-button type="primary" @click="submitForm(ruleFormRef)">提交</el-button>
            <el-button @click="resetForm(ruleFormRef)">重置</el-button>
        </el-form-item>
    </el-form>
</template>

<script setup>
import { reactive, ref } from 'vue'
import { FormInstance } from 'element-plus'
import axios from 'axios'
//前端必须设置此项，后台session才能获取到值
axios.defaults.withCredentials = true;

const ruleFormRef = ref(FormInstance)

//记录前端输入的验证码变量
const ruleForm = reactive({
    verifiCode: '',
})

//页面加载时获取图片
const url = ref('http://localhost:8081/testMybatis/getVerifiCode')

//点击图片时获取新验证码
const getVerifiCode = () => {
    //让参数随机可切换验证码(重新生成，避免浏览器缓存)
    url.value = 'http://localhost:8081/testMybatis/getVerifiCode?' + new Date().getTime();
}


const checkVerifiCode = (rule, value, callback) => {
    if (!value) {
        return callback(new Error('请输入验证码'))
    } else {
        //验证码不为空时去后台验证
        axios.post('http://localhost:8081/testMybatis?verifiCode=' + ruleForm.verifiCode).then((res) => {
            if (res.data == "error") {
                return callback(new Error('验证码错误'))
            } else {
                callback()
            }
        })
    }
}


//校验
const rules = reactive({
    verifiCode: [{ validator: checkVerifiCode }]
})
//提交
const submitForm = (formEl) => {
    if (!formEl) return
    formEl.validate((valid) => {
        if (valid) {
            alert('提交成功')
        } else {
            alert('提交失败')
            return false
        }
    })
}
//重置
const resetForm = (formEl) => {
    if (!formEl) return
    formEl.resetFields()
}
</script>
